package cn.moonspace.flowerowner.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;

import cn.moonspace.common.util.MyJsonUtil;
import cn.moonspace.flowerowner.entities.Comment;
import cn.moonspace.flowerowner.entities.Upload;
import cn.moonspace.flowerowner.exception.DriverException;
import cn.moonspace.flowerowner.service.CommentService;

@Service("commentService")
public class CommentServiceImpl extends BaseService implements CommentService {

	@Override
	public JSONObject addComment(String ip, String content, Long uploadID)
			throws DriverException {
		JSONObject json = new JSONObject();
		
		Comment comment = new Comment();
		comment.setIp(ip);
		comment.setContent(content);
		comment.setCreateDate(new Date());
		Upload upload = uploadRepository.findOne(uploadID);
		comment.setUpload(upload);
		commentRepository.save(comment);
		
		Comment result = new Comment();
		try{
			result = comment.clone();
		} catch (CloneNotSupportedException e) {
			DriverException de = new DriverException(DriverException.CommentCloneException, "Comment Clone Error: " + e.getMessage(), this.getClass().getName());
			de.setStackTrace(e.getStackTrace());
			throw de;
		}
        JSONObject commentJson = JSONObject.fromObject(result, MyJsonUtil.getConfig("yyyy-MM-dd HH:mm:ss"));
		json.put("result", commentJson);
		return json;
	}

	@Override
	public JSONObject getCommentsByUpload(Long uploadID)
			throws DriverException {
		
		JSONObject result = new JSONObject();
		
		Upload upload = uploadRepository.findOne(uploadID);
		Sort sort = new Sort(new Order(Direction.DESC,"createDate"));
		List<Comment> comments = commentRepository.findCommentsByUpload(upload, sort);
		
		List<Comment> results = new ArrayList<Comment>();
		
		if(comments == null || comments.isEmpty()){
			result.put("error", "没有评论");
		}else{
			for(Comment comment : comments){
				try {
					results.add(comment.clone());
				} catch (CloneNotSupportedException e) {
					DriverException de = new DriverException(DriverException.CommentCloneException, "Comment Clone Error: " + e.getMessage(), this.getClass().getName());
					de.setStackTrace(e.getStackTrace());
					throw de;
				}
			}
			JSONArray arrUploads = JSONArray.fromObject(results, MyJsonUtil.getConfig("yyyy-MM-dd HH:mm:ss"));
			result.put("results", arrUploads);
		}
		
		return result;
	} 

	
}
